package uit.nfc.utils;

import java.util.ArrayList;

import uit.nfc.nfcmenudishes.NfcMenuActivity;
import uit.nfc.nfcmenudishes.R;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;

public class GetAllDishesAsyncTask extends AsyncTask<Void, ArrayList<DishesItem>, String> {

	private Context context;
	private ProgressDialog progressDialog;
	private ArrayList<DishesItem> dishesItems = null;
	
	public GetAllDishesAsyncTask(Context context) {
		this.context = context;
	}
	
	@Override
	protected void onPreExecute() {
		this.progressDialog = ProgressDialog.show(context, "Loading...", "Please wait..."); 
	}

	@Override
	protected String doInBackground(Void... params) {
		String response = WebServiceHelper.callWebService("http://restaurant-webservice.appspot.com/resources/item");
		return response;
	}

	@Override
	protected void onPostExecute(String result) {
		this.progressDialog.cancel();
		
		dishesItems = JSONParser.parseAllDishesItems(result);
		
		if (dishesItems != null) {
			int length = dishesItems.size();
			DishesItem[] dishes = new DishesItem[length + 1];
			dishes[0] = new DishesItem();
			
			for (int i = 1; i <= length; ++i) {
				dishes[i] = dishesItems.get(i - 1);
			}
			
			ArrayAdapter spinnerAdapter = new SpinnerAdapter(context, R.layout.spinner_row, dishes);
			((NfcMenuActivity)context).getSpinnerDishes().setAdapter(spinnerAdapter);
		}
	}
}
